<template>
  <div
    class="full-box bg-white d-flex"
    v-loading="loading"
  >
    <LeftTool
      @changeMap="changeMap"
      @changeDlMap="changeDlMap"
      @addBaseMapData="addBaseMapData"
      @switchLayerVisible="switchLayerVisible"
      @addMapItem="addMapItem"
      @updateMapFeatures="updateMapFeatures"
      @exportData="exportData"
      @previewImage="previewImage"
      @fit="fitFeatureById"
      @calculateBoundary="calculateBoundary"
      @changeContainerStyle="changeContainerStyle"
      @toggleLegend="toggleLegend"
      @toggleCompass="toggleCompass"
      @toggleShowTitle="toggleShowTitle"
      @toggleShowBzdw="toggleShowBzdw"
      @toggleShowBzrq="toggleShowBzrq"
      @toggleShowText="toggleShowText"
      @changeLayerStyle="changeLayerStyle"
      @renderYlMap="renderYlMap"
    />
    <div
      class="flex-1 overflow-hidden position-relative map-working-space"
      ref="fullContainer"
    >
      <div
        :class="['boundary', showBoundary ? 'show' : '']"
        :style="boundaryStyle"
      >
        <div
          class="full-box position-relative"
          ref="mapContainer"
        >
          <BKGeoMap
            ref="geoMap"
            @onloadMap1="onloadMap"
            :need-remote-layer="false"
            :url="mapUrl"
          />
          <LegendContainer
            v-model="legendVisible"
            :list="list"
            :container-width="containerWidth"
            :container-height="containerHeight"
            ref="legendContainer"
          />
          <TitleContainer
            v-model="titleVisible"
            :container-width="containerWidth"
            :container-height="containerHeight"
            ref="titleContainer"
          />
          <BzdwContainer
            v-model="bzdwVisible"
            :container-width="containerWidth"
            :container-height="containerHeight"
            ref="bzdwContainer"
          />
          <BzrqContainer
            v-model="bzrqVisible"
            :container-width="containerWidth"
            :container-height="containerHeight"
            ref="bzrqContainer"
          />
          <CompassContainer
            v-model="compassVisible"
            :container-width="containerWidth"
            :container-height="containerHeight"
            ref="compassContainer"
          />
          <MapTool
            style="position: absolute;right: 8px;top: 0;"
            @setZoom="setZoom"
            @confirmLocate="confirmLocate"
          />
          <YlLegend
            style="position: absolute;top: 50%; transform: translateY(-100%);"
            v-model="ylLegendVisible"
            :list="ylLegendList"
          />
        </div>
        <!-- <div class="map-coordinates f-12">
          <span class="m-r-mini">{{ mapName }}</span>
          <span class="m-r-mini">级别： {{ Math.floor(zoom) }}</span>
          <span>经纬度： {{ pointer[0].toFixed(6) + ',' + pointer[1].toFixed(6) }}</span>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { startCreateImg, layerStyleFunctionById, changeShowAllText, sizeMap } from './utils'
import LegendContainer from './components/legend-container'
import TitleContainer from './components/title-container'
import BzdwContainer from './components/bzdw-container'
import BzrqContainer from './components/bzrq-container'
import CompassContainer from './components/compass-container'
import LeftTool from './components/left-tool'
import MapTool from './components/map-tool.vue'
import YlLegend from './components/yl-legend.vue'

import { mapState } from 'vuex'
import { debounce } from 'throttle-debounce'
import { publicPath } from '@/configs'

export default {
  name: 'ThematicMapMaking',
  components: {
    LegendContainer,
    TitleContainer,
    BzdwContainer,
    BzrqContainer,
    CompassContainer,
    LeftTool,
    MapTool,
    YlLegend
  },
  data () {
    return {
      list: [],
      legendVisible: false,
      exportLegendVisible: true,
      compassVisible: true,
      titleVisible: false,
      bzdwVisible: false,
      bzrqVisible: false,
      containerWidth: 0,
      containerHeight: 0,
      loading: false,
      mapList: [
        { bklayerId: 'tianditu_sl', bklayerType: 'tianditu', bklayerName: '天地图（矢量）', bklayerSn: 1, visible: false, props: { bklayerTiandituType: 'vec_c' } },
        { bklayerId: 'tianditu_sldl', bklayerType: 'tianditu', bklayerName: '天地图（矢量道路）', bklayerSn: 11, visible: false, props: { bklayerTiandituType: 'cva_c' } },
        { bklayerId: 'tianditu_yx', bklayerType: 'tianditu', bklayerName: '天地图（影像）', bklayerSn: 2, visible: false, props: { bklayerTiandituType: 'img_c' } },
        { bklayerId: 'tianditu_yxdl', bklayerType: 'tianditu', bklayerName: '天地图（影像道路）', bklayerSn: 12, visible: false, props: { bklayerTiandituType: 'cia_c' } },
        { bklayerId: 'tianditu_dx', bklayerType: 'tianditu', bklayerName: '天地图（地形）', bklayerSn: 3, visible: true, props: { bklayerTiandituType: 'ter_c' } },
        { bklayerId: 'tianditu_dxdl', bklayerType: 'tianditu', bklayerName: '天地图（地形道路）', bklayerSn: 13, visible: false, props: { bklayerTiandituType: 'cta_c' } },
        { bklayerId: 'gaode', bklayerType: 'gaode', bklayerName: '高德', bklayerSn: 4, visible: false, props: { bklayerGaodeStyle: '6' } },
        { bklayerId: 'gaodedl', bklayerType: 'gaode', bklayerName: '高德道路', bklayerSn: 14, visible: false, props: { bklayerGaodeStyle: '8' } }
      ],
      currentMap: 'tianditu_dx',
      showDl: false,
      currentSn: 100,
      itemCurrentSn: 200,
      showBoundary: false,
      boundaryStyle: {
        width: '100%',
        height: '100%'
      },
      showText: true,
      mapUrl: publicPath + 'config/map-making-config.json',
      ylLegendVisible: false,
      ylLegendList: []
    }
  },
  computed: {
    ...mapState('map', ['zoom', 'pointer']),
    ...mapState('map-making', ['baseLayer', 'boundaryLayer', 'stationLayer', 'projectLayer', 'exportExtent', 'titleData', 'legendData', 'otherData', 'dateData', 'stationTextOption', 'projectTextOption', 'compassPosition']),
    ...mapState('user', ['userInfo']),
    mapName () {
      const item = this.mapList.find(m => m.bklayerId === this.currentMap)
      return item.bklayerName
    }
  },
  created () {
    this.$root.$on('updateMapMaking', this.updateMapMaking)
    this.debounceCommitCompassPosition = debounce(50, this.commitCompassPosition)
  },
  beforeDestroy () {
    this.$root.$off('updateMapMaking', this.updateMapMaking)
  },
  methods: {
    updateMapMaking () {
      setTimeout(() => {
        if (this.exportExtent) {
          this.$refs.geoMap.fit(this.exportExtent, { duration: 0 })
        }
      }, 200)
    },
    updateLegend () {
      const allLayers = this.map.layerManager.getAllLayer()
      this.list = []
      const maskLayer = this.map.mapUtil.getLayer('maskLayer')
      const hasMask = maskLayer && maskLayer.getSource().getFeatures().length
      for (const layerId of allLayers) {
        const layer = this.map.mapUtil.getLayer(layerId)
        if (layer.get('needLegend') && layer.getVisible() && layer.getSource().getFeatures().length) {
          if (hasMask && (layerId.startsWith('ly-') || layerId.startsWith('xz-'))) continue
          this.list.push({ text: layer.values_.bklayerName, layerId: layerId })
        }
      }
      if (this.exportLegendVisible) {
        this.legendVisible = !!(this.exportLegendVisible && this.list.length)
      }
    },
    onloadMap (map) {
      this.map = map
      this.containerHeight = this.$refs.mapContainer.offsetHeight
      this.containerWidth = this.$refs.mapContainer.offsetWidth
      this.createLayers()
      this.$refs.geoMap.setZoom('quanmao')
      // this.toggleCompass()
      this.createMenuItems()
    },
    async createLayers () {
      this.$refs.geoMap.addLayers(this.mapList)
      const layers = await this.$refs.geoMap.addLayers([{
        bklayerId: 'maskLayer',
        bklayerType: 'vectorlayer',
        bklayerName: '蒙层',
        bklayerSn: 199,
        visible: true
      }])
      layers[0].setStyle(new window.ol.style.Style({
        fill: new window.ol.style.Fill({ color: '#fff' }),
        stroke: new window.ol.style.Stroke({ color: '#ccc', width: 4 })
      }))
    },
    toggleLegend (value) {
      this.exportLegendVisible = value === '1'
      if (value === '1') {
        this.updateLegend()
      }
      this.legendVisible = !!(value === '1' && this.list.length)
    },
    toggleShowTitle (value) {
      this.titleVisible = value === '1'
    },
    toggleShowBzdw (value) {
      this.bzdwVisible = value === '1'
    },
    toggleShowBzrq (value) {
      this.bzrqVisible = value === '1'
    },
    toggleShowText (value) {
      this.showText = value === '1'
      const allLayers = this.map.layerManager.getAllLayer()
      changeShowAllText(this.showText)
      allLayers.forEach(layerId => {
        const layer = this.map.mapUtil.getLayer(layerId)
        if (layer.get('needLegend')) {
          layer.setStyle(layerStyleFunctionById(layerId))
          layer.getSource().forEachFeature(feature => {
            feature.setStyle(layerStyleFunctionById(layerId))
            feature.changed()
          })
        }
      })
    },
    toggleCompass (value) {
      this.compassVisible = value === '1'
      // if (!this.compassControl) {
      //   this.compassControl = new window.ol.control.Compass({
      //     src: require('./compass.svg'),
      //     className: 'compass-position',
      //     visible: true,
      //     style: new window.ol.style.Stroke({ color: 'black' })
      //   })
      //   this.map.addControl(this.compassControl)
      // } else {
      //   this.compassControl.setVisible(value === '1')
      // }
    },
    previewImage (formData, sizes) {
      this.loading = true
      const allLayers = this.map.layerManager.getAllLayer()
      return new Promise(resolve => {
        let legendRatio = null
        let compassRatio = null
        let titleRatio = null
        let bzdwRatio = null
        let bzrqRatio = null
        let scale = 1
        const mapRect = this.$refs.mapContainer.getBoundingClientRect()
        if (this.legendVisible && this.list.length) {
          const legendRect = this.$refs.legendContainer.$el.getBoundingClientRect()
          legendRatio = {
            width: legendRect.width / mapRect.width,
            height: legendRect.height / mapRect.height,
            left: (legendRect.left - mapRect.left) / mapRect.width,
            top: (legendRect.top - mapRect.top) / mapRect.height
          }
        }
        if (this.titleVisible && this.titleData.title) {
          const titleRect = this.$refs.titleContainer.$el.getBoundingClientRect()
          titleRatio = {
            left: (titleRect.left - mapRect.left) / mapRect.width,
            top: (titleRect.top - mapRect.top) / mapRect.height
          }
        }
        if (this.bzdwVisible && this.otherData.bzdw) {
          const bzdwRect = this.$refs.bzdwContainer.$el.getBoundingClientRect()
          bzdwRatio = {
            left: (bzdwRect.left - mapRect.left) / mapRect.width,
            top: (bzdwRect.top - mapRect.top) / mapRect.height
          }
        }
        if (this.bzrqVisible && this.dateData.bzrq) {
          const bzrqRect = this.$refs.bzrqContainer.$el.getBoundingClientRect()
          bzrqRatio = {
            left: (bzrqRect.left - mapRect.left) / mapRect.width,
            top: (bzrqRect.top - mapRect.top) / mapRect.height
          }
        }
        if (this.compassVisible) {
          const compassRect = this.$refs.compassContainer.$el.getBoundingClientRect()
          // const element = document.querySelector('.ol-compassctrl.compass-position')
          // const compassRect = element.getBoundingClientRect()
          compassRatio = {
            width: compassRect.width / mapRect.width,
            height: compassRect.height / mapRect.height,
            left: (compassRect.left - mapRect.left) / mapRect.width,
            top: (compassRect.top - mapRect.top) / mapRect.height
          }
        }

        const { extent } = this.map.getView().getViewStateAndExtent()
        if (sizes) {
          scale = sizes[0] / mapRect.width
          allLayers.forEach(layerId => {
            const layer = this.map.mapUtil.getLayer(layerId)
            if (layer.get('needLegend')) {
              layer.setStyle(layerStyleFunctionById(layerId))
              layer.getSource().forEachFeature(feature => {
                const styles = feature.getStyle()
                if (styles && Array.isArray(styles)) {
                  styles.forEach(style => {
                    if (style.getText()) {
                      const textStyle = style.getText()
                      textStyle.setFont(`bold ${Math.round(parseInt(textStyle.getFont().split(' ')[1]) * scale)}px sans-serif`)
                      textStyle.setOffsetY(Math.round(textStyle.getOffsetY() * scale))
                    }
                    if (style.getStroke()) {
                      style.getStroke().setWidth(Number((style.getStroke().getWidth() * scale).toFixed(2)))
                    }
                    if (style.getImage()) {
                      style.getImage().setScale(Number((0.8 * scale).toFixed(2)))
                    }
                  })
                  feature.changed()
                }
              })
            }
          })
          this.boundaryStyle.width = sizes[0] + 'px'
          this.boundaryStyle.height = sizes[1] + 'px'
          // if (formData.ZNZ_XS === '1') {
          //   const element = document.querySelector('.ol-compassctrl.compass-position')
          //   element.style.width = compassRatio.width * sizes[0] + 'px'
          //   element.style.height = compassRatio.height * sizes[1] + 'px'
          //   element.style.left = compassRatio.left * sizes[0] + 'px'
          //   element.style.top = compassRatio.top * sizes[1] + 'px'
          // }
        }
        setTimeout(async () => {
          if (sizes) {
            this.$refs.geoMap.fit(extent, { duration: 0 })
          }
          const file = await startCreateImg({
            map: this.map,
            legendContainer: this.legendVisible ? this.$refs.legendContainer.$el : null,
            titleContainer: this.titleVisible && this.titleData.title ? this.$refs.titleContainer.$el : null,
            bzdwContainer: this.bzdwVisible && this.otherData.bzdw ? this.$refs.bzdwContainer.$el : null,
            bzrqContainer: this.bzrqVisible && this.dateData.bzrq ? this.$refs.bzrqContainer.$el : null,
            compassContainer: this.compassVisible ? this.$refs.compassContainer.$el : null,
            mapContainer: this.$refs.mapContainer,
            legendRatio,
            titleRatio,
            bzdwRatio,
            bzrqRatio,
            compassRatio,
            scale
          })
          this.changeContainerStyle(this.sizes)
          setTimeout(() => {
            if (sizes) {
              // if (formData.ZNZ_XS === '1') {
              //   const element = document.querySelector('.ol-compassctrl.compass-position')
              //   element.style.width = '70px'
              //   element.style.height = '70px'
              //   element.style.left = this.compassPosition.left * this.$refs.mapContainer.offsetWidth
              //   element.style.top = this.compassPosition.top * this.$refs.mapContainer.offsetHeight
              // }
              this.$refs.geoMap.fit(extent, { duration: 0 })
              allLayers.forEach(layerId => {
                const layer = this.map.mapUtil.getLayer(layerId)
                if (layer.get('needLegend')) {
                  layer.setStyle(layerStyleFunctionById(layerId))
                  layer.getSource().forEachFeature(feature => {
                    const styles = feature.getStyle()
                    if (styles && Array.isArray(styles)) {
                      styles.forEach(style => {
                        if (style.getText()) {
                          const textStyle = style.getText()
                          textStyle.setFont(`bold ${Math.round(parseInt(textStyle.getFont().split(' ')[1]) / scale)}px sans-serif`)
                          textStyle.setOffsetY(Math.round(textStyle.getOffsetY() / scale))
                        }
                        if (style.getStroke()) {
                          style.getStroke().setWidth((layerId.startsWith('ly-') || layerId.startsWith('xz-')) ? 4 : 2)
                        }
                        if (style.getImage()) {
                          style.getImage().setScale(0.8)
                        }
                      })
                      feature.changed()
                    }
                  })
                }
              })
            }
            this.loading = false
            resolve({ file, extent })
          }, 200)
        }, 200)
      })
    },
    async exportData (formData, sizes) {
      const { file, extent } = await this.previewImage(formData, sizes)
      const json = { baseLayer: this.baseLayer, boundaryLayer: this.boundaryLayer, stationLayer: this.stationLayer, projectLayer: this.projectLayer, exportExtent: extent, legendData: this.legendData, titleData: this.titleData, otherData: this.otherData, dateData: this.dateData, stationTextOption: this.stationTextOption, projectTextOption: this.projectTextOption, compassPosition: this.compassPosition }
      console.log(json)
      formData.IDSJSON = JSON.stringify(json)
      const [{ filePath }] = await this.$request.upload('/file/uploads', {
        file,
        branchPath: 'common'
      })
      formData.WJLJ = filePath
      await this.$request.singleTableOperation({
        metaSet: 'YSQJC_ZTT_XXBC',
        methodCode: 'insert',
        methodParams: { ...formData, CJBM: this.userInfo.dept.LEADER }
      })
      this.$message.success('导出成功')
    },
    setZoom (type) {
      this.$refs.geoMap.setZoom(type)
    },
    confirmLocate (location, info) {
      this.$refs.geoMap.setCenterAndZoom(location)
      this.map.tipsPopup.show(location, `<div>${info.address || info.name}</div>`)
    },
    changeMap (type, oldType) {
      const typeMap = {
        1: 'tianditu_sl',
        2: 'tianditu_yx',
        3: 'tianditu_dx',
        4: 'gaode'
      }
      this.currentMap = typeMap[type]
      this.$refs.geoMap.setLayerVisible(typeMap[type], true)
      this.$refs.geoMap.setLayerVisible(typeMap[oldType], false)
      if (this.showDl) {
        this.$refs.geoMap.setLayerVisible(typeMap[type] + 'dl', true)
        this.$refs.geoMap.setLayerVisible(typeMap[oldType] + 'dl', false)
      }
    },
    changeDlMap (value) {
      this.showDl = value
      this.$refs.geoMap.setLayerVisible(this.currentMap + 'dl', value)
    },
    addBaseMapData (list) {
      // 基础地图图层
      this.timer = setInterval(() => {
        if (this.map) {
          const data = list.map(item => ({
            bklayerId: 'base-' + item.type,
            bklayerSn: item.sn,
            bklayerType: item.layerType,
            visible: item.visible ?? false,
            bklayerUrl: item.layerUrl,
            bklayerName: item.text,
            ...item.props
          }))
          this.$refs.geoMap.addLayers(data)
          clearInterval(this.timer)
        }
      }, 200)
    },
    switchLayerVisible (layerId, value) {
      const layer = this.map.mapUtil.getLayer(layerId)
      layer.setVisible(value)
    },
    addMapItem ({ layerId, value, kjdx, layerName, updating }) {
      const allLayers = this.map.layerManager.getAllLayer()
      let feature
      if (allLayers.includes(layerId)) {
        const layer = this.map.mapUtil.getLayer(layerId)
        const features = layer.getSource().getFeatures()
        feature = features[0]
        layer.setVisible(value)
      } else {
        feature = this.$refs.geoMap.transfromFeature(kjdx)
        this.$refs.geoMap.addLayers([{
          bklayerId: layerId,
          bklayerSn: this.currentSn,
          bklayerType: 'vectorlayer_empty',
          visible: true,
          bklayerName: layerName
        }])
        const layer = this.map.mapUtil.getLayer(layerId)
        layer.set('needLegend', true, false)
        layer.setStyle(layerStyleFunctionById(layerId))
        this.currentSn++
        layer.getSource().addFeature(feature)
      }
      this.updateLegend()
      if (value && !updating) {
        // 当回显更新时无需fit
        this.$refs.geoMap.fit(feature.getGeometry(), { padding: [100, 100, 100, 400] })
      }
    },
    updateMapFeatures ({ layerId, rows, layerName }) {
      let layer = this.map.mapUtil.getLayer(layerId)
      if (!layer) {
        // 创建图层
        this.$refs.geoMap.addLayers([{
          bklayerId: layerId,
          bklayerSn: this.itemCurrentSn,
          bklayerType: 'vectorlayer_empty',
          visible: true,
          bklayerName: layerName
        }])
        layer = this.map.mapUtil.getLayer(layerId)
        layer.set('needLegend', true, false)
        layer.setStyle(layerStyleFunctionById(layerId))
        this.itemCurrentSn++
      }
      this.updateFeaturesByLayer(layer, rows)
      this.updateLegend()
      if (layerId.startsWith('station-')) {
        this.changeLayerStyle({ layerId, textOption: this.stationTextOption[layerId] })
      } else if (layerId.startsWith('gc-')) { this.changeLayerStyle({ layerId, textOption: this.projectTextOption[layerId] }) }
    },
    // 比对更新features
    updateFeaturesByLayer (layer, rows) {
      let hasErrorData = false
      const features = layer.getSource().getFeatures()
      const add = []
      const removeFeatures = []
      const featureIds = features.map(item => item.getId())
      const rowIds = rows.map(item => item.id)
      for (const row of rows) {
        if (!featureIds.includes(row.id)) {
          // features里需要新增的feature
          add.push(row)
        }
      }
      for (const feature of features) {
        if (!rowIds.includes(feature.getId())) {
          // features里需要移除的feature
          removeFeatures.push(feature)
        }
      }
      // 更新操作
      removeFeatures.forEach(feature => {
        layer.getSource().removeFeature(feature)
      })
      const addFeatures = []
      add.forEach(row => {
        if (row.kjdx) {
          const feature = this.$refs.geoMap.transfromFeature(row.kjdx)
          feature.setId(row.id)
          feature.setProperties({ text: row.text })
          addFeatures.push(feature)
        } else if (row.coordinates) {
          const geom = new window.ol.geom.Point(row.coordinates)
          const feature = new window.ol.Feature(geom)
          feature.setId(row.id)
          feature.setProperties({ text: row.text })
          addFeatures.push(feature)
        } else {
          hasErrorData = true
        }
      })
      layer.getSource().addFeatures(addFeatures)
      if (hasErrorData) {
        this.$message.error('本次选择有没有空间矢量信息的数据，标红显示')
      }
    },
    fitFeatureById (id, layerId) {
      console.log(id, layerId)
      const layer = this.map.mapUtil.getLayer(layerId)
      if (layer) {
        const feature = layer.getSource().getFeatureById(id)
        if (feature) {
          this.$refs.geoMap.fit(feature.getGeometry(), { padding: [100, 100, 100, 800] })
        }
      }
    },
    compareArraysHasDiff (arr1, arr2) {
      // 比较数组差异，有差异返回true
      let diff = arr1.filter(item => !arr2.includes(item))
      diff = diff.concat(arr2.filter(item => !arr1.includes(item)))
      return !!diff.length
    },
    async calculateBoundary (value) {
      const layer = this.map.mapUtil.getLayer('maskLayer')
      layer && layer.getSource().clear()
      if (value) {
        const { lyCurrent, xzCurrent } = this.boundaryLayer
        if (!lyCurrent.length && !xzCurrent.length) {
          this.$message.warning('请先选择边界')
          return
        }
        if (!(this.lyCurrent && !this.compareArraysHasDiff(lyCurrent, this.lyCurrent) && xzCurrent && !this.compareArraysHasDiff(xzCurrent, this.xzCurrent))) {
          // 优化体验，比较边界，如果边界没有变化，直接使用缓存的wkt
          this.lyCurrent = lyCurrent
          this.xzCurrent = xzCurrent
          const data = await this.$request.post('/ysjc/ztt/selectKjdxs', {
            XZQDMS: xzCurrent.join(','),
            CODES: lyCurrent.join(',')
          })
          this.maskWkt = data.KJDX
        }
        const extent = window.turf.bboxPolygon([-180, -90, 180, 90])
        const feature = this.$refs.geoMap.transfromFeature(this.maskWkt)
        const geoJson = this.map.bkol.feature2GeoJson(feature)
        const resultFeature = this.map.bkol.geoJson2feature(window.turf.difference(extent, geoJson))
        layer.getSource().addFeature(resultFeature)
        // 该方法可用，但不能处理大量数据集合的面
        // const lyLayers = lyCurrent.map(id => {
        //   return this.map.mapUtil.getLayer('ly-' + id)
        // }).filter(l => l.getVisible())
        // const xzLayers = xzCurrent.map(id => {
        //   return this.map.mapUtil.getLayer('xz-' + id)
        // }).filter(l => l.getVisible())
        // console.log(lyLayers, xzLayers)
        // const extent = window.turf.bboxPolygon([-180, -90, 180, 90])
        // let resultLyJson = null
        // let resultXzJson = null
        // if (!lyLayers.length && !xzLayers.length) {
        //   this.$message.warning('请先选择边界')
        //   return
        // }
        // if (lyLayers.length > 1) {
        //   const featuresJson = lyLayers.map(item => this.map.bkol.feature2GeoJson(item.getSource().getFeatures()[0]))
        //   resultLyJson = window.turf.union(...featuresJson)
        // } else if (lyLayers.length === 1) {
        //   resultLyJson = this.map.bkol.feature2GeoJson(lyLayers[0].getSource().getFeatures()[0])
        // }
        // if (xzLayers.length > 1) {
        //   const featuresJson = xzLayers.map(item => this.map.bkol.feature2GeoJson(item.getSource().getFeatures()[0]))
        //   resultXzJson = window.turf.union(...featuresJson)
        // } else if (xzLayers.length === 1) {
        //   resultXzJson = this.map.bkol.feature2GeoJson(xzLayers[0].getSource().getFeatures()[0])
        // }
        // if (resultLyJson && resultXzJson) {
        //   const intersection = window.turf.intersect(resultLyJson, resultXzJson)
        //   if (intersection) {
        //     const resultFeature = this.map.bkol.geoJson2feature(window.turf.difference(extent, intersection))
        //     layer.getSource().addFeature(resultFeature)
        //   } else {
        //     this.$message.warning('边界没有交界处')
        //   }
        // } else {
        //   if (!resultLyJson) {
        //     const resultFeature = this.map.bkol.geoJson2feature(window.turf.difference(extent, resultXzJson))
        //     layer.getSource().addFeature(resultFeature)
        //   }
        //   if (!resultXzJson) {
        //     const resultFeature = this.map.bkol.geoJson2feature(window.turf.difference(extent, resultLyJson))
        //     layer.getSource().addFeature(resultFeature)
        //   }
        // }
      }
      this.updateLegend()
    },
    changeContainerStyle (sizes) {
      this.showBoundary = !!sizes
      this.sizes = sizes
      if (sizes) {
        const height = this.$refs.fullContainer.offsetHeight * 0.9
        const ratio = sizes[0] / sizes[1]
        if ((height * ratio) > this.$refs.fullContainer.offsetWidth) {
          this.boundaryStyle.width = this.$refs.fullContainer.offsetWidth + 'px'
          this.boundaryStyle.height = this.$refs.fullContainer.offsetWidth / ratio + 'px'
        } else {
          this.boundaryStyle.width = height * ratio + 'px'
          this.boundaryStyle.height = height + 'px'
        }
      } else {
        this.boundaryStyle.width = '100%'
        this.boundaryStyle.height = '100%'
      }
      setTimeout(() => {
        this.containerWidth = this.$refs.mapContainer.offsetWidth
        this.containerHeight = this.$refs.mapContainer.offsetHeight
      }, 200)
    },
    createMenuItems () {
      this.$refs.geoMap.setContextMenuMethod((feature, layerId, event) => {
        this.currentFeature = feature
        this.currentLayerId = layerId
        if (layerId.startsWith('station-') || layerId.startsWith('gc-')) {
          return [
            { text: '移除', callback: this.removeFeature }
          ]
        }
        return []
      })
    },
    removeFeature () {
      const layer = this.map.mapUtil.getLayer(this.currentLayerId)
      console.log(this.currentFeature)
      layer.getSource().removeFeature(this.currentFeature)
      const id = this.currentFeature.getId()
      this.$root.$emit('removeCurrentRow', { id, layerId: this.currentLayerId })
    },
    changeLayerStyle ({ layerId, textOption }) {
      const layer = this.map.mapUtil.getLayer(layerId)
      if (!layer) return
      layer.setStyle(layerStyleFunctionById(layerId, { ...textOption, fontSize: sizeMap[textOption.fontSize] }))
      layer.getSource().forEachFeature(feature => {
        feature.setStyle(layerStyleFunctionById(layerId, { ...textOption, fontSize: sizeMap[textOption.fontSize] }))
        feature.changed()
      })
    },
    async renderYlMap ({ polygons, rainRange, rangeColor, visible }) {
      let layer = this.map.mapUtil.getLayer('yl_layer')
      if (!layer) {
        [layer] = await this.$refs.geoMap.addLayers([{
          bklayerId: 'yl_layer',
          bklayerType: 'vectorlayer',
          bklayerName: '雨量分布',
          bklayerSn: 50,
          visible: true
        }])
      }
      layer.getSource().clear()
      if (!visible) {
        this.ylLegendVisible = false
        return
      }

      const geoJsonFormat = new window.ol.format.GeoJSON() // 创建GeoJSON格式化对象
      const features = geoJsonFormat.readFeatures(polygons)
      console.log(features)
      features.forEach(feature => {
        const properties = feature.getProperties()
        feature.setStyle(new window.ol.style.Style({
          fill: new window.ol.style.Fill({ color: properties.fillColor })
        }))
      })
      layer.getSource().addFeatures(features)
      this.ylLegendList = rangeColor.map((item, i) => ({ text: rainRange[i], color: item }))
      this.ylLegendVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.map-working-space {
  ::v-deep .ol-scale-line {
    bottom: 10px;
  }

  .map-coordinates {
    background: rgba(#fff, 0.8);
    color: #76778c;
    padding: 8px 20px;
    position: absolute;
    right: 0;
    bottom: 0;
    border-radius: 4px 0 0;
  }
}

.boundary {
  &.show {
    position: absolute;
    border: 1px solid #000;
    z-index: 8;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    overflow: hidden;
  }
}
</style>
